//
//  MJRefreshHeaderView.m
//  MJRefresh
//
//  Created by mj on 13-2-26.
//  Copyright (c) 2013年 itcast. All rights reserved.
//  下拉刷新

#import "MJRefreshConst.h"
#import "MJRefreshHeaderView.h"

#define DEVICE_IS_IPHONE6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define DEVICE_IS_IPHONE5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define DEVICE_IS_IPHONE4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)


@interface MJRefreshHeaderView()
// 最后的更新时间
@property (nonatomic, strong) NSDate *lastUpdateTime;
@end

@implementation MJRefreshHeaderView

+ (instancetype)header
{
    return [[MJRefreshHeaderView alloc] init];
}

#pragma mark - UIScrollView相关
#pragma mark 重写设置ScrollView
- (void)setScrollView:(UIScrollView *)scrollView
{

    [super setScrollView:scrollView];
    // 1.设置边框
    self.frame = CGRectMake(0, - MJRefreshViewHeight, scrollView.frame.size.width, MJRefreshViewHeight);
    
    // 2.加载时间
    self.lastUpdateTime = [[NSUserDefaults standardUserDefaults] objectForKey:MJRefreshHeaderTimeKey];
}

#pragma mark - 状态相关
#pragma mark 设置最后的更新时间
- (void)setLastUpdateTime:(NSDate *)lastUpdateTime
{
    _lastUpdateTime = lastUpdateTime;
    
    // 1.归档
    [[NSUserDefaults standardUserDefaults] setObject:_lastUpdateTime forKey:MJRefreshHeaderTimeKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 2.更新时间
    [self updateTimeLabel];
}

#pragma mark 更新时间字符串
- (void)updateTimeLabel
{
//    if (!_lastUpdateTime) return;
//    
//    // 1.获得年月日
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
//    NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:_lastUpdateTime];
//    NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]];
//    
//    // 2.格式化日期
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    if ([cmp1 day] == [cmp2 day]) { // 今天
//        formatter.dateFormat = @"今天 HH:mm";
//    } else if ([cmp1 year] == [cmp2 year]) { // 今年
//        formatter.dateFormat = @"MM-dd HH:mm";
//    } else {
//        formatter.dateFormat = @"yyyy-MM-dd HH:mm";
//    }
//    NSString *time = [formatter stringFromDate:_lastUpdateTime];
    
    // 3.显示日期
//    _lastUpdateTimeLabel.text = [NSString stringWithFormat:@"最后更新：%@", time];
}

- (void)setScrollViewY:(CGFloat)scrollViewY{

    float scro_y = (0-scrollViewY)-100;
    float w1     = 5;
    float w2     = 16;
    float Y      = 50;
    float X      = (self.frame.size.width-w2*2)/2+1.5;
    float ww     = scro_y/Y*(w2-w1)+w1;

    if (scro_y<=Y) {
        centerHeartImage.hidden = YES;
        leftHeartImage.hidden  = NO;
        rigthHeartImage.hidden = NO;
        leftHeartImage.frame   = CGRectMake(scro_y/Y*X, 44-ww*2, ww,ww/16*25);
        rigthHeartImage.frame  = CGRectMake(self.frame.size.width-scro_y/Y*X-ww, 44-ww*2, ww,ww/16*25);
    }else{
        centerHeartImage.hidden = NO;

        leftHeartImage.hidden  = YES;
        rigthHeartImage.hidden = YES;

        float leftX = 0,rightX = 0;
        if (DEVICE_IS_IPHONE4||DEVICE_IS_IPHONE5) {leftX = 145.5;rightX = 159;}
        if (DEVICE_IS_IPHONE6) {leftX = 173;rightX = 186;}
        else {leftX = 192.5;rightX = 205;}
        
        leftHeartImage.frame   = CGRectMake(leftX, 12,16, 25);
        rigthHeartImage.frame  = CGRectMake(rightX, 12,16, 25);
    }
}
#pragma mark 设置状态
- (void)setState:(MJRefreshState)state
{

    // 1.一样的就直接返回
    if (_state == state) return;
    
    // 2.保存旧状态
    MJRefreshState oldState = _state;
    
    // 3.调用父类方法
    [super setState:state];
    
    // 4.根据状态执行不同的操作
	switch (state) {
		case MJRefreshStatePulling: // 松开可立即刷新
        {
            // 设置文字
            _statusLabel.text = NSLocalizedString(@"可以松手了", @"");
            // 执行动画
            [UIView animateWithDuration:MJRefreshAnimationDuration animations:^{
                _arrowImage.transform = CGAffineTransformMakeRotation(M_PI);
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = _scrollViewInitInset.top;
                _scrollView.contentInset = inset;
                
                leftHeartImage.hidden = YES;
                rigthHeartImage.hidden = YES;
//                leftHeartImage.frame  = CGRectMake(0,0,0,0);
//                rigthHeartImage.frame = CGRectMake(0,0,0,0);
//
//                centerHeartImage.hidden = YES;
//                centerHeartImage.frame =  CGRectMake((self.frame.size.width-43)/2, 12,43, 37.5);

            }];
			break;
        }
            
		case MJRefreshStateNormal: // 下拉可以刷新
        {
            // 设置文字
			_statusLabel.text = NSLocalizedString(@"下拉刷新", @"");
            // 执行动画
            [UIView animateWithDuration:MJRefreshAnimationDuration animations:^{
                _arrowImage.transform = CGAffineTransformIdentity;
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = _scrollViewInitInset.top;
                _scrollView.contentInset = inset;
                
                leftHeartImage.hidden = NO;
                rigthHeartImage.hidden = NO;
//                leftHeartImage.frame  = CGRectMake(50, 5, 50, 50);
//                rigthHeartImage.frame = CGRectMake(self.frame.size.width-100, 5, 50, 50);
//                centerHeartImage.hidden = YES;
//                centerHeartImage.frame =  CGRectMake((self.frame.size.width-50)/2, 5, 50.0, 50.0);
            }];
            
            // 刷新完毕
            if (MJRefreshStateRefreshing == oldState) {
                // 保存刷新时间
                leftHeartImage.hidden = YES;
                rigthHeartImage.hidden = YES;
                leftHeartImage.frame  = CGRectMake(0,0,0,0);
                rigthHeartImage.frame = CGRectMake(0,0,0,0);

                centerHeartImage.hidden = NO;
                centerHeartImage.frame =  CGRectMake((self.frame.size.width-43)/2, 12,43, 37.5);

                self.lastUpdateTime = [NSDate date];
            }
			break;
        }
            
		case MJRefreshStateRefreshing: // 正在刷新中
        {

            // 设置文字
            _statusLabel.text = NSLocalizedString(@"正在刷新…", @"");
            // 执行动画
            [UIView animateWithDuration:MJRefreshAnimationDuration animations:^{
                _arrowImage.transform = CGAffineTransformIdentity;
                // 1.增加65的滚动区域
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = _scrollViewInitInset.top + MJRefreshViewHeight;
                _scrollView.contentInset = inset;
                // 2.设置滚动位置
                _scrollView.contentOffset = CGPointMake(0, - _scrollViewInitInset.top - MJRefreshViewHeight);
                leftHeartImage.hidden = YES;
                rigthHeartImage.hidden = YES;
                
                centerHeartImage.hidden = NO;
                centerHeartImage.frame =  CGRectMake((self.frame.size.width-43)/2, 12,43, 37.5);
            }];
			break;
        }
            
        default:
            break;
	}
}

#pragma mark - 在父类中用得上
// 合理的Y值(刚好看到下拉刷新控件时的contentOffset.y，取相反数)
- (CGFloat)validY
{
    return _scrollViewInitInset.top;
}

// view的类型
- (int)viewType
{
    return MJRefreshViewTypeHeader;
}
@end